<template>
  <div class="user-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="text-2xl font-bold text-gray-800">用户权限管理</h1>
      <p class="text-gray-500 mt-1">管理系统用户及其权限配置</p>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar bg-white rounded-lg shadow-sm p-4 mb-6">
      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <!-- 搜索框 -->
        <div class="relative w-full md:w-64">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索用户..."
            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
            @keyup.enter="fetchUsers"
          >
          <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
        </div>

        <!-- 筛选器 -->
        <div class="flex flex-wrap items-center gap-3">
          <select
            v-model="roleFilter"
            class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
            @change="fetchUsers"
          >
            <option value="">所有角色</option>
            <option v-for="role in roles" :key="role.id" :value="role.id">{{ role.name }}</option>
          </select>

          <select
            v-model="statusFilter"
            class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
            @change="fetchUsers"
          >
            <option value="">所有状态</option>
            <option value="active">活跃</option>
            <option value="inactive">禁用</option>
          </select>

          <button
            class="ml-auto bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-all flex items-center gap-2"
            @click="showAddUserModal = true"
          >
            <i class="fa fa-plus"></i>
            <span>新增用户</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-list bg-white rounded-lg shadow-sm overflow-hidden">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                用户名
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                邮箱
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                角色
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                状态
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                最后登录
              </th>
              <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <template v-if="loading">
              <tr v-for="i in 5" :key="i" class="animate-pulse">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-6 bg-gray-200 rounded w-32"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-6 bg-gray-200 rounded w-48"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-6 bg-gray-200 rounded w-24"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-6 bg-gray-200 rounded w-16"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-6 bg-gray-200 rounded w-32"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right">
                  <div class="h-8 bg-gray-200 rounded w-24 ml-auto"></div>
                </td>
              </tr>
            </template>

            <template v-else-if="users && users.length === 0">
              <tr>
                <td colspan="6" class="px-6 py-12 text-center text-gray-500">
                  <div class="flex flex-col items-center">
                    <i class="fa fa-user-friends text-4xl mb-3 text-gray-300"></i>
                    <p>没有找到匹配的用户</p>
                    <button
                      class="mt-2 text-blue-600 hover:text-blue-800 text-sm"
                      @click="resetFilters"
                    >
                      重置筛选条件
                    </button>
                  </div>
                </td>
              </tr>
            </template>

            <template v-else>
              <tr 
                v-for="user in users" 
                :key="user.id"
                class="hover:bg-gray-50 transition-colors"
              >
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="flex items-center">
                    <div class="h-10 w-10 rounded-full bg-gray-200 flex items-center justify-center mr-3">
                      <span class="text-gray-600 font-medium">{{ user.name.charAt(0) }}</span>
                    </div>
                    <div>
                      <div class="text-sm font-medium text-gray-900">{{ user.name }}</div>
                      <div class="text-xs text-gray-500">{{ user.id }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm text-gray-900">{{ user.email }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span 
                    class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                    :class="roleClass(user.role)"
                  >
                    {{ user.role.name }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span 
                    class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                    :class="user.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"
                  >
                    {{ user.status === 'active' ? '活跃' : '禁用' }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ user.lastLogin ? formatDate(user.lastLogin) : '从未登录' }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <button
                    class="text-blue-600 hover:text-blue-900 mr-3"
                    @click="editUser(user)"
                  >
                    编辑
                  </button>
                  <button
                    class="text-purple-600 hover:text-purple-900 mr-3"
                    @click="managePermissions(user)"
                  >
                    权限
                  </button>
                  <button
                    class="text-red-600 hover:text-red-900"
                    @click="confirmDeactivate(user)"
                  >
                    {{ user.status === 'active' ? '禁用' : '启用' }}
                  </button>
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="px-6 py-3 border-t border-gray-200 flex items-center justify-between">
        <div class="text-sm text-gray-500">
          显示 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, totalUsers) }} 条，共 {{ totalUsers }} 条
        </div>
        <div class="flex space-x-2">
          <button
            class="px-3 py-1 border border-gray-300 rounded-md text-sm"
            :disabled="currentPage === 1"
            @click="currentPage = currentPage - 1"
          >
            上一页
          </button>
          <button
            class="px-3 py-1 border border-gray-300 rounded-md text-sm"
            :disabled="currentPage >= totalPages"
            @click="currentPage = currentPage + 1"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑用户模态框 -->
    <EditUserModal
      :visible="showEditUserModal"
      :user="selectedUser"
      :roles="roles"
      @close="showEditUserModal = false"
      @save="handleSaveUser"
    />

    <!-- 添加用户模态框 -->
    <AddUserModal
      :visible="showAddUserModal"
      :roles="roles"
      @close="showAddUserModal = false"
      @save="handleAddUser"
    />

    <!-- 权限管理模态框 -->
    <PermissionManagementModal
      :visible="showPermissionModal"
      :user="selectedUser"
      :permissions="allPermissions"
      @close="showPermissionModal = false"
      @save="handleSavePermissions"
    />

    <!-- 确认操作模态框 -->
    <ConfirmModal
      :visible="showConfirmModal"
      :title="confirmTitle"
      :message="confirmMessage"
      @close="showConfirmModal = false"
      @confirm="handleConfirmAction"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import EditUserModal from './components/EditUserModal.vue';
import AddUserModal from './components/AddUserModal.vue';
import PermissionManagementModal from './components/PermissionManagementModal.vue';
import ConfirmModal from '@/components/ConfirmDialog.vue';
import { useUserStore } from '@/stores/userStore';
import { usePermissionStore } from '@/stores/permissionStore';
import { formatDate } from '@/utils/date';

export default {
  components: {
    EditUserModal,
    AddUserModal,
    PermissionManagementModal,
    ConfirmModal
  },
  setup() {
    // 状态管理
    const userStore = useUserStore();
    const permissionStore = usePermissionStore();

    // 数据状态
    const users = ref([]);
    const roles = ref([]);
    const allPermissions = ref([]);
    const loading = ref(false);
    const totalUsers = ref(0);
    
    // 筛选状态
    const searchQuery = ref('');
    const roleFilter = ref('');
    const statusFilter = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    
    // 模态框状态
    const showEditUserModal = ref(false);
    const showAddUserModal = ref(false);
    const showPermissionModal = ref(false);
    const showConfirmModal = ref(false);
    const selectedUser = ref(null);
    const userToDeactivate = ref(null);
    
    // 确认框信息
    const confirmTitle = ref('');
    const confirmMessage = ref('');

    // 计算属性
    const totalPages = computed(() => {
      return Math.ceil(totalUsers.value / pageSize.value);
    });

    // 获取用户列表
    const fetchUsers = async () => {
      try {
        loading.value = true;
        const params = {
          page: currentPage.value,
          limit: pageSize.value,
          search: searchQuery.value,
          roleId: roleFilter.value,
          status: statusFilter.value
        };
        
        const response = await userStore.getUsers(params);
        users.value = response.data;
        totalUsers.value = response.total;
      } catch (error) {
        console.error('获取用户列表失败:', error);
        // 可以在这里添加错误提示
      } finally {
        loading.value = false;
      }
    };

    // 获取角色列表
    const fetchRoles = async () => {
      try {
        const response = await userStore.getRoles();
        roles.value = response;
      } catch (error) {
        console.error('获取角色列表失败:', error);
      }
    };

    // 获取所有权限
    const fetchPermissions = async () => {
      try {
        const response = await permissionStore.getAllPermissions();
        allPermissions.value = response;
      } catch (error) {
        console.error('获取权限列表失败:', error);
      }
    };

    // 初始化数据
    const initData = async () => {
      await Promise.all([
        fetchUsers(),
        fetchRoles(),
        fetchPermissions()
      ]);
    };

    // 编辑用户
    const editUser = (user) => {
      selectedUser.value = { ...user };
      showEditUserModal.value = true;
    };

    // 管理权限
    const managePermissions = async (user) => {
      try {
        selectedUser.value = { ...user };
        // 获取用户当前权限
        const userPermissions = await permissionStore.getUserPermissions(user.id);
        selectedUser.value.permissions = userPermissions;
        showPermissionModal.value = true;
      } catch (error) {
        console.error('获取用户权限失败:', error);
      }
    };

    // 确认禁用/启用用户
    const confirmDeactivate = (user) => {
      userToDeactivate.value = user;
      const action = user.status === 'active' ? '禁用' : '启用';
      confirmTitle.value = `${action}用户`;
      confirmMessage.value = `确定要${action}用户 "${user.name}" 吗？${action === '禁用' ? '禁用后用户将无法登录系统。' : ''}`;
      showConfirmModal.value = true;
    };

    // 处理确认操作
    const handleConfirmAction = async () => {
      if (!userToDeactivate.value) return;

      try {
        const newStatus = userToDeactivate.value.status === 'active' ? 'inactive' : 'active';
        await userStore.updateUserStatus(userToDeactivate.value.id, newStatus);
        // 刷新用户列表
        fetchUsers();
        // 可以在这里添加成功提示
      } catch (error) {
        console.error('更新用户状态失败:', error);
        // 可以在这里添加错误提示
      } finally {
        showConfirmModal.value = false;
        userToDeactivate.value = null;
      }
    };

    // 保存用户编辑
    const handleSaveUser = async (updatedUser) => {
      try {
        await userStore.updateUser(updatedUser.id, updatedUser);
        // 刷新用户列表
        fetchUsers();
        showEditUserModal.value = false;
        // 可以在这里添加成功提示
      } catch (error) {
        console.error('更新用户失败:', error);
        // 可以在这里添加错误提示
      }
    };

    // 添加新用户
    const handleAddUser = async (newUser) => {
      try {
        await userStore.createUser(newUser);
        // 刷新用户列表
        fetchUsers();
        showAddUserModal.value = false;
        // 可以在这里添加成功提示
      } catch (error) {
        console.error('创建用户失败:', error);
        // 可以在这里添加错误提示
      }
    };

    // 保存用户权限
    const handleSavePermissions = async (userId, permissions) => {
      try {
        await permissionStore.updateUserPermissions(userId, permissions);
        showPermissionModal.value = false;
        // 可以在这里添加成功提示
      } catch (error) {
        console.error('更新用户权限失败:', error);
        // 可以在这里添加错误提示
      }
    };

    // 重置筛选条件
    const resetFilters = () => {
      searchQuery.value = '';
      roleFilter.value = '';
      statusFilter.value = '';
      currentPage.value = 1;
      fetchUsers();
    };

    // 角色样式类
    const roleClass = (role) => {
      const roleClasses = {
        'admin': 'bg-purple-100 text-purple-800',
        'editor': 'bg-blue-100 text-blue-800',
        'viewer': 'bg-gray-100 text-gray-800',
        'guest': 'bg-yellow-100 text-yellow-800'
      };
      return roleClasses[role.code] || 'bg-gray-100 text-gray-800';
    };

    // 页面加载时初始化
    onMounted(() => {
      initData();
    });

    return {
      users,
      roles,
      allPermissions,
      loading,
      totalUsers,
      searchQuery,
      roleFilter,
      statusFilter,
      currentPage,
      pageSize,
      totalPages,
      showEditUserModal,
      showAddUserModal,
      showPermissionModal,
      showConfirmModal,
      selectedUser,
      confirmTitle,
      confirmMessage,
      fetchUsers,
      editUser,
      managePermissions,
      confirmDeactivate,
      handleConfirmAction,
      handleSaveUser,
      handleAddUser,
      handleSavePermissions,
      resetFilters,
      roleClass,
      formatDate
    };
  }
};
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.action-bar {
  margin-bottom: 24px;
}

.user-list {
  margin-bottom: 24px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .action-bar .flex {
    flex-direction: column;
    align-items: stretch;
  }
  
  .user-list table {
    font-size: 14px;
  }
  
  .user-list th,
  .user-list td {
    padding: 8px 12px;
  }
}
</style>
